<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>
    <div class="order-summary">
      <div class="order-summary-item" @click="handSwitchStatus(null)"
        ><n-button>全部订单:{{ orderSummary.all }}</n-button>
      </div>
      <div class="order-summary-item" @click="handSwitchStatus(1)"
        ><n-button type="primary">待支付:{{ orderSummary.waitPay }}</n-button></div
      >
      <div class="order-summary-item" @click="handSwitchStatus(2)"
        ><n-button type="info">待确认收款:{{ orderSummary.waitConfirm }}</n-button></div
      >
      <div class="order-summary-item" @click="handSwitchStatus(3)"
        ><n-button type="warning">待上架:{{ orderSummary.waitPutSale }}</n-button></div
      >
      <div class="order-summary-item" @click="handSwitchStatus(4)"
        ><n-button type="success">已上架:{{ orderSummary.alreadyPutSale }}</n-button></div
      >
      <div class="order-summary-item" @click="handSwitchStatus(5)"
        ><n-button type="error">已取消:{{ orderSummary.alreadyCancel }}</n-button></div
      >
    </div>
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      :row-class-name="rowClassName"
      :scroll-x="1090"
      size="small"
    >
      <template #tableTitle>
        <!-- <n-button type="primary" @click="selectGoods">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          添加商品
        </n-button> -->
      </template>

      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>
    <n-modal
      v-model:show="showPickUpInfoModal"
      :show-icon="false"
      preset="dialog"
      title="提货信息"
      style="width: 500px"
    >
      <n-space vertical>
        <div>商品名称：{{ currentOrder.goodsName }} </div>
        <div>收货姓名：{{ currentOrder.name }}</div>
        <div>收货手机：{{ currentOrder.mobile }}</div>
        <div>收货地址：{{ currentOrder.areaName }}-{{ currentOrder.address }}</div>
      </n-space>
    </n-modal>

    <n-modal
      v-model:show="showPutSaleModal"
      :show-icon="false"
      preset="dialog"
      title="上架"
      style="width: 500px"
    >
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="卖家姓名" path="sellerName">
          <n-input placeholder="" readonly="true" v-model:value="formParams.sellerName" />
        </n-form-item>
        <n-form-item label="当前订单" path="orderSn">
          <n-input placeholder="" readonly="true" v-model:value="formParams.orderSn" />
        </n-form-item>
        <n-form-item label="商品原价" path="originalPrice">
          <n-input-number
            placeholder=""
            :readonly="true"
            v-model:value="formParams.originalPrice"
          />
        </n-form-item>
        <n-form-item label="服务费" path="servicePrice">
          <n-input-number placeholder="" :readonly="true" v-model:value="formParams.servicePrice" />
        </n-form-item>
        <n-form-item label="销售价格" path="newPrice">
          <n-input-number placeholder="请输入上架价格" v-model:value="formParams.newPrice" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="() => (showPutSaleModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmPutSaleForm"
            >确定</n-button
          >
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { onMounted, h, reactive, ref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { BasicTable, TableAction } from '@/components/Table';
  import {
    getRushPurchaseOrderPage,
    cancelOrder,
    getRushPurchaseOrderSummary,
    orderConfirmReceipt,
    getPutSaleInfo,
    putSale,
  } from '@/api/promotion/rushPurchaseOrder';
  import { getMemberDefAddress } from '@/api/member/member';
  import { columns } from './lib/orderColumns';
  import { ResultEnum } from '@/enums/httpEnum';

  const message = useMessage();
  const params = ref({});
  const actionRef = ref();
  const dialog = useDialog();
  const showPickUpInfoModal = ref(false); // 显示提货信息弹窗
  const showPutSaleModal = ref(false); // 显示上架弹窗
  const currentOrder = ref(); // 当前订单
  const formBtnLoading = ref(false);
  const orderSummary = reactive({
    all: 0,
    waitPay: 0,
    waitConfirm: 0,
    waitPutSale: 0,
    alreadyPutSale: 0,
    alreadyCancel: 0,
  });

  const rules = {
    rushPurchaseDetailId: {
      required: true,
      message: '请输入活动ID',
      trigger: 'blur',
    },
    newPrice: {
      required: true,
      message: '请输入销售价格',
      trigger: 'blur',
      type: 'number',
      validator: (_rule: any, value: number) => {
        if (value === 0 || value < 0 || value === null || value === undefined) {
          return Promise.reject('请输入销售价格');
        } else {
          return Promise.resolve();
        }
      },
    },
  };
  const formRef: any = ref(null);
  const formParams = reactive({
    originalPrice: 0,
    newPrice: 0,
    servicePrice: 0,
    orderSn: '',
    sellerName: '',
    memberId: 0,
    rushPurchaseDetailId: 0,
  });
  const formParamsBak = { ...formParams };

  const schemas: FormSchema[] = [
    {
      field: 'buyerName',
      component: 'NInput',
      label: '买家姓名',
      rules: [{ required: false }],
    },
    {
      field: 'buyerMobile',
      component: 'NInput',
      label: '买家手机号',
      rules: [{ required: false }],
    },
    {
      field: 'sellerName',
      component: 'NInput',
      label: '卖家姓名',
      rules: [{ required: false }],
    },
    {
      field: 'sellerMobile',
      component: 'NInput',
      label: '卖家手机号',
      rules: [{ required: false }],
    },
    {
      field: 'buyTime',
      component: 'NDatePicker',
      label: '下单时间',
      componentProps: {
        type: 'datetimerange',
        defaultTime: ['00:00:00', '23:59:59'],
      },
      rules: [{ required: false }],
    },
    {
      field: 'isPickUp',
      component: 'NSelect',
      label: '是否提货',
      componentProps: {
        placeholder: '请选择状态',
        options: [
          {
            label: '未提货',
            value: 0,
          },
          {
            label: '已提货',
            value: 1,
          },
        ],
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: false }],
    },
  ];
  const actionColumn = reactive({
    width: 180,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      let action: any[] = [];
      if (record.status == 1) {
        action.push({
          label: '取消订单',
          type: 'error',
          onClick: handleCancel.bind(null, record),
        });
      }
      if (record.status == 2) {
        action.push({
          label: '查看凭证',
          type: 'primary',
          onClick: function () {
            window.open(record.payProof, '_blank');
          },
        });

        action.push({
          label: '确认收款',
          onClick: handleConfirmReceipt.bind(null, record),
        });
      }
      if (record.isPickUp == 1) {
        action.push({
          label: '提货信息',
          type: 'primary',
          onClick: handlePickUpInfoModalOpen.bind(null, record),
        });
      }
      if (record.status == 3 && record.isPickUp == 0) {
        action.push({
          label: '上架',
          type: 'primary',
          onClick: handlePutSaleModalOpen.bind(null, record),
        });
      }
      return h(TableAction as any, {
        style: 'button',
        actions: action,
      });
    },
  });

  const loadDataTable = async (res) => {
    return await getRushPurchaseOrderPage({ ...params.value, ...res });
  };

  function handSwitchStatus(status) {
    console.log(status);
    params.value = { ...params.value, status };
    reloadTable();
  }

  async function handlePutSaleModalOpen(record) {
    const result = await getPutSaleInfo({ id: record.id });
    formParams.originalPrice = record.price;
    formParams.sellerName = record.buyerName;
    formParams.orderSn = record.orderSn;
    formParams.memberId = record.buyerId;
    formParams.rushPurchaseDetailId = record.id;
    formParams.servicePrice = result.priceService;
    formParams.newPrice = result.sellPrice;
    showPutSaleModal.value = true;
  }

  async function handlePickUpInfoModalOpen(record) {
    const result = await getMemberDefAddress({ memberId: record.buyerId });
    currentOrder.value = { ...record, ...result };
    console.log(currentOrder.value);
    showPickUpInfoModal.value = true;
    console.log(showPickUpInfoModal.value);
  }

  /**
   * 订单上架（无需用户发起申请）
   * @param e
   */
  function confirmPutSaleForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      console.log(errors);
      if (!errors) {
        let params = { id: formParams.rushPurchaseDetailId, price: formParams.newPrice };
        let response = await putSale(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          Object.assign(formParams, formParamsBak);
          showPutSaleModal.value = false;
          reloadTable();
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleConfirmReceipt(record) {
    dialog.info({
      title: '提示',
      content: `您确定想确认收款吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await orderConfirmReceipt(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  function handleCancel(record) {
    console.log(record, '点击了取消');
    dialog.info({
      title: '提示',
      content: `您确定想取消吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await cancelOrder(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function rowClassName(row) {
    if (row.status === 5) {
      return 'detail-cancel';
    }
    return '';
  }

  const [register, {}] = useForm({
    //gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    gridProps: { cols: '2 s:2 m:3 l:5 xl:6 2xl:6' },
    labelWidth: 80,
    schemas,
  });

  function handleSubmit(values: Recordable) {
    console.log(values);
    params.value = { ...values };
    console.log({ ...params.value });
    reloadTable();
  }

  function handleReset(values: Recordable) {
    params.value = [];
    console.log(values);
    reloadTable();
  }

  onMounted(async () => {
    const result = await getRushPurchaseOrderSummary();
    orderSummary.all = result.allOrder;
    orderSummary.waitPay = result.buyOrder;
    orderSummary.waitConfirm = result.payOrder;
    orderSummary.waitPutSale = result.confirmOrder;
    orderSummary.alreadyPutSale = result.putSaleOrder;
    orderSummary.alreadyCancel = result.cancelOrder;
  });
</script>

<style lang="less" scoped>
  //取消订单颜色
  :deep(.detail-cancel .status) {
    color: #f00 !important;
  }

  .order-summary {
    &-title {
      font-size: 18px;
      font-weight: bold;
    }

    &-item {
      margin: 0 10px;
      font-size: 17px;
      cursor: pointer; //鼠标移上去变成手指
      float: left;
    }
  }
</style>
